package com.zxl.manager.privacy.utils.base;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

import com.umeng.message.PushAgent;
import com.zxl.manager.privacy.utils.track.MobclickAgentHelper;

import java.util.ArrayList;
import java.util.List;

/**
 * 基础Activity
 * Created by Administrator on 2016/4/21.
 */
public class BaseAppCompatActivity extends AppCompatActivity implements BaseAppCompatFragment.BackHandledInterface {

    private boolean mIsMainActivity = false;

    private static List<BaseAppCompatActivity> sList;

    protected BaseAppCompatFragment mBackHandedFragment;

    static {
        if (sList == null) {
            sList = new ArrayList<>();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        PushAgent.getInstance(this).onAppStart();
        sList.add(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgentHelper.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgentHelper.onPause(this);
    }

    /**
     * 设置主Activity
     *
     * @param mIsMainActivity
     */
    public void setMainActivity(boolean mIsMainActivity) {
        this.mIsMainActivity = mIsMainActivity;
    }

    @Override
    protected void onDestroy() {
        sList.remove(this);
        super.onDestroy();
        if (mIsMainActivity) {
            MobclickAgentHelper.onKillProcess(this);
            if (null != sList && !sList.isEmpty()) {
                for (BaseAppCompatActivity baseActivity : sList) {
                    baseActivity.finish();
                }
            }
            android.os.Process.killProcess(android.os.Process.myPid());
        }
    }

    @Override
    public void setSelectedFragment(BaseAppCompatFragment selectedFragment) {
        mBackHandedFragment = selectedFragment;
    }

    @Override
    public void onBackPressed() {
        if (null != mBackHandedFragment) {
            if (!mBackHandedFragment.onBackPressed()) {
                if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
                    super.onBackPressed();
                } else {
                    getSupportFragmentManager().popBackStack();
                }
            }
        } else {
            super.onBackPressed();
        }
    }
}
